package gov.pr.celepar.sentinela.admin.action;

import java.util.Collection;

import gov.pr.celepar.sentinela.Constants;
import gov.pr.celepar.sentinela.admin.excecao.SentinelaServerException;
import gov.pr.celepar.sentinela.admin.facade.SistemaFacade;
import gov.pr.celepar.sentinela.admin.form.BaseForm;
import gov.pr.celepar.sentinela.admin.pojo.Sistema;
import gov.pr.celepar.sentinela.client.SentinelaLogin;
import gov.pr.celepar.sentinela.comunicacao.SentinelaComunicacao;
import gov.pr.celepar.sentinela.comunicacao.SentinelaInterface;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public abstract class BaseAction extends Action {
	protected final String INCLUIR = "incluir";

	protected final String CONF_INCLUIR = "conf_incluir";

	protected final String ALTERAR = "alterar";

	protected final String CONF_ALTERAR = "conf_alterar";

	protected final String EXCLUIR = "excluir";

	protected final String CONF_EXCLUIR = "conf_excluir";

	protected final String CONSULTAR = "consultar";

	protected final String MSG_SUCESS = "MENSAGEM";

	protected final String MSG_ERROR = "APPLICATION_EXCEPTION";

	protected final String MSG_EXCEPTION = "EXCEPTION";

	protected final String MSG_ALERT = "ALERT_MESSAGE";

	protected final String SALVAR = "salvar";

	protected String forward;

	protected ServletContext context;

	protected HttpSession session;

	protected SentinelaInterface comunicacao;

	private static Log logger = LogFactory.getLog(BaseAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		this.session = request.getSession(false);

		this.comunicacao = SentinelaComunicacao.getInstance(request);

		SentinelaLogin login = (SentinelaLogin) this.session
				.getAttribute(Constants.SESSION_SENTINELA_LOGIN);
		this.context = super.getServlet().getServletContext();
		try {
			this.forward = this.executar(mapping, form, request, response);
		} catch (SentinelaServerException ssex) {
			logger.error(login.getUsuario().getNome() + "-"
					+ login.getUsuario().getCodUsuario() + " - "
					+ request.getLocalAddr() + " - " + request.getRequestURI()
					+ " - " + ssex.getMessage(), ssex.getCausaRaiz());

			this.addMessageError(ssex, request);

		} catch (Exception excecao) {
			logger.error(login.getUsuario().getNome() + "-"
					+ login.getUsuario().getCodUsuario() + " - "
					+ request.getLocalAddr() + " - " + request.getRequestURI(),
					excecao);
			excecao.printStackTrace();
			this.addMessageException(excecao, request);
			if (!trataExcecao(excecao, mapping, form, request, response)) {
				this.addMessageException(excecao, request);
			}
		}
		ActionForward af = mapping.findForward(this.forward);
		return af;
	}

	protected boolean trataExcecao(Exception e, ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		boolean res = false;
		BaseForm frm = (BaseForm) form;
		String msg = e.getMessage();
		String erroFk = "viola restrição de chave estrangeira";
		if (msg != null && msg.indexOf(erroFk) != -1) {
			res = true;
			if (this.CONF_ALTERAR.equalsIgnoreCase(frm.getAcao()))
				frm.setAcao(this.ALTERAR);
			if (this.CONF_INCLUIR.equalsIgnoreCase(frm.getAcao()))
				frm.setAcao(this.INCLUIR);
			if (this.CONF_EXCLUIR.equalsIgnoreCase(frm.getAcao()))
				frm.setAcao(this.EXCLUIR);
			this.forward = this.executar(mapping, frm, request, response);
			String msgUser = this.getResources(request).getMessage("erroFk");
			this
					.addMessageError(new SentinelaServerException(msgUser),
							request);
		}
		return res;
	}

	public abstract String executar(
			org.apache.struts.action.ActionMapping mapping,
			org.apache.struts.action.ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception;

	protected void addMessageSucess(String msg, HttpServletRequest request) {
		if (msg != null && msg.length() > 0) {
			request.setAttribute(this.MSG_SUCESS, msg);
		}
	}

	protected void addMessageError(SentinelaServerException sentinelaEx,
			HttpServletRequest request) {
		if (sentinelaEx != null) {
			request.setAttribute(this.MSG_ERROR, sentinelaEx);
		}
	}

	protected void addMessageException(Exception ex, HttpServletRequest request) {
		if (ex != null) {
			request.setAttribute(this.MSG_EXCEPTION, ex);
		}
	}

	protected void addMessageAlert(String msg, HttpServletRequest request) {
		if (msg != null && msg.length() > 0) {
			request.setAttribute(this.MSG_ALERT, msg);
		}
	}

	/**
	 * Método utilizado pelas demais subclasses quando necessário carregar as
	 * opções da combo de sistemas.
	 * 
	 * @param request
	 * @throws SentinelaServerException
	 * @throws Exception
	 */
	protected void listarSistemasAutorizados(HttpServletRequest request)
			throws SentinelaServerException, Exception {

		Collection<Sistema> sistemas = SistemaFacade
				.listarSistemasAutorizados(this.comunicacao);

		request.setAttribute("listaSistemas", sistemas);
	}
}